package com.lvyou.filter;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lvyou.entity.Admin;
import com.lvyou.entity.UserModel;
import com.lvyou.model.JsonResult;
import com.lvyou.util.UrlKit;

public class UserAuthFilter implements Filter {

	private static List<String> notFilterPath=new ArrayList();
	static {
		notFilterPath.add("/js/*");//支持通配符*
		notFilterPath.add("/css/*");
		notFilterPath.add("/login.html");
		notFilterPath.add("/doLogin");
	}

	@Override
	public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain fc)
			throws IOException, ServletException {
		HttpServletRequest req=(HttpServletRequest)arg0;
		HttpServletResponse resp=(HttpServletResponse)arg1;
		HttpSession session=req.getSession();
		String servletPath = req.getServletPath();
		
		boolean b=isNotFilter(req);
		
		if(b) {
			fc.doFilter(arg0, arg1);
			return;
		}
		
		UserModel um=(UserModel)session.getAttribute("userInfo");
		if(um!=null) {
			fc.doFilter(arg0, arg1);
			return;
		}else {
			if("/order/check".equals(servletPath)) {
				String url=UrlKit.getURL(req);
				resp.sendRedirect(url+"/login.html");
				
			}else if(servletPath.matches("/order/.*.html")) {
				String url=UrlKit.getURL(req);
				resp.sendRedirect(url+"/login.html");
				
			}else {
				JsonResult jr=new JsonResult(300,"请登录");
				ObjectMapper om=new ObjectMapper();
				String json=om.writeValueAsString(jr);
				
				resp.setCharacterEncoding("UTF-8");
				resp.setContentType("application/json; charset=utf-8");
				PrintWriter out = resp.getWriter();
				out.println(json);
				out.flush();
			}
			return;
		}

	}
	
	private boolean isNotFilter(HttpServletRequest req) {
		String servletPath = req.getServletPath();
		for (String path:notFilterPath) {
			path=path.replaceAll("\\*", "\\.\\*");//将*替换成.*，然后进行正则表达式匹配
			if(servletPath.matches(path)){
				return true;
			}
		}
		return false;
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}
}
